class_name CardUI
extends Control

#重新父化，否则会受限于Hand的边界框内
signal reparent_requested(which_card_ui: CardUI)

const BASE_STYLEBOX := preload("res://scenes/card_ui/card_base_stylebox.tres")
const DRAG_STYLEBOX := preload("res://scenes/card_ui/card_dragging_stylebox.tres")
const HOVER_STYLEBOX := preload("res://scenes/card_ui/card_hover_stylebox.tres")

@export var player_modifiers: ModifierHandler
@export var card: Card : set = _set_card
@export var char_stats: CharacterStats : set = _set_char_stats

@onready var card_visuals: CardVisuals = $CardVisuals
@onready var drop_point_detector: Area2D = $DropPointDetector
@onready var card_state_machine: CardStateMachine = $CardStateMachine
@onready var targets: Array[Node] = []

var original_index := 0
var parent: Control
var tween: Tween
var playable := true : set = _set_playable
var disabled := false


func _ready() -> void:
	Events.card_aim_started.connect(_on_card_drag_or_aiming_started)
	Events.card_drag_started.connect(_on_card_drag_or_aiming_started)
	Events.card_drag_ended.connect(_on_card_drag_or_aiming_ended)
	Events.card_aim_ended.connect(_on_card_drag_or_aiming_ended)
	card_state_machine.init(self)

#只有状态机可以处理输入
func _input(event: InputEvent) -> void:
	card_state_machine.on_input(event)


func animate_to_position(new_position: Vector2, duration: float) -> void:
	tween = create_tween().set_trans(Tween.TRANS_CIRC).set_ease(Tween.EASE_OUT)
	tween.tween_property(self, "global_position", new_position, duration)


func play() -> void:
	if not card:
		return
		
	# 记录卡牌类型和当前使用次数，用于调试
	print("准备播放卡牌 %s, 最大次数: %d, 当前次数: %d" % [card.id, card.card_max_repeat_num, card.card_current_repeat_num])
	card.play(targets, char_stats, player_modifiers)
	# 无论哪种类型的卡牌，都销毁UI元素
	print("卡牌 %s 使用完成，销毁UI" % card.id)
	queue_free()


func get_active_enemy_modifiers() -> ModifierHandler:
	if targets.is_empty() or targets.size() > 1 or not targets[0] is Enemy:
		return null
	
	return targets[0].modifier_handler


func request_tooltip() -> void:
	var enemy_modifiers := get_active_enemy_modifiers()
	var updated_tooltip := card.get_updated_tooltip(player_modifiers, enemy_modifiers)
	Events.card_tooltip_requested.emit(card.icon, updated_tooltip)


func _on_gui_input(event: InputEvent) -> void:
	card_state_machine.on_gui_input(event)


func _on_mouse_entered() -> void:
	card_state_machine.on_mouse_entered()


func _on_mouse_exited() -> void:
	card_state_machine.on_mouse_exited()


func _set_card(value: Card) -> void:
	if not is_node_ready():
		await ready
	
	card = value
	card_visuals.card = card
	# 确保费用显示正确（即使没有targets，也会显示基础费用）
	card_visuals.update_cost_display()

func _set_playable(value: bool) -> void:
	playable = value
	if not playable:
		card_visuals.cost.add_theme_color_override("font_color", Color.RED)
		card_visuals.icon.modulate = Color(1, 1, 1, 0.5)
	else:
		card_visuals.cost.remove_theme_color_override("font_color")
		card_visuals.icon.modulate = Color(1, 1, 1, 1)


func _set_char_stats(value: CharacterStats) -> void:
	char_stats = value
	char_stats.stats_changed.connect(_on_char_stats_changed)


func _on_drop_point_detector_area_entered(area: Area2D) -> void:
	if not targets.has(area):
		targets.append(area)
		# 当targets变化时，更新费用显示
		card_visuals.update_cost_display(targets)

func _on_drop_point_detector_area_exited(area: Area2D) -> void:
	targets.erase(area)
	# 当targets变化时，更新费用显示
	card_visuals.update_cost_display(targets)


func _on_card_drag_or_aiming_started(used_card: CardUI) -> void:
	if used_card == self:
		return
	
	disabled = true

func _on_card_drag_or_aiming_ended(_card: CardUI) -> void:
	disabled = false
	# 恢复强制重新检查，确保卡牌的可玩性状态与当前能量状态保持同步
	# 这样可以避免在拖动结束后卡牌状态不一致的问题
	var old_playable = playable
	# 使用新的方法，考虑修改器影响
	if char_stats and player_modifiers:
		playable = char_stats.can_play_card_with_modifiers(card, player_modifiers)
	else:
		playable = char_stats.can_play_card(card) if char_stats else false
	
	# 添加调试信息，帮助追踪拖动结束后的状态更新
	if old_playable != playable:
		print("🔄 拖动结束后卡牌UI %s 可玩性状态更新: %s → %s" % [
			card.id if card else "未知",
			"可打出" if old_playable else "不可打出",
			"可打出" if playable else "不可打出"
		])

func _on_char_stats_changed() -> void:
	var old_playable = playable
	# 使用新的方法，考虑修改器影响
	if char_stats and player_modifiers:
		playable = char_stats.can_play_card_with_modifiers(card, player_modifiers)
	else:
		playable = char_stats.can_play_card(card) if char_stats else false
	
	# 添加调试信息，帮助追踪状态变化
	if old_playable != playable:
		print("🔄 卡牌UI %s 可玩性状态变化: %s → %s" % [
			card.id if card else "未知",
			"可打出" if old_playable else "不可打出",
			"可打出" if playable else "不可打出"
		])
